import React, { useEffect, useRef, useState } from 'react'
import "./style.less"
import {withRouter} from "react-router-dom"
import {useSelector, useDispatch} from "react-redux"
import * as searchAction from "../../redux/actions/search"
import {useParams} from "react-router-dom"

function SearchInput(props) {
  const [keywords, setKeywords] =  useState("")
  const searchKey = useRef()
  const dispatch = useDispatch()
  const reduxKeywords = useSelector(state => state.search)
  const params = useParams()

  const keyUpHandle = (e) =>{
    // console.log(e);
    if(keywords.length>0){
      if(e.keyCode === 13){
        props.history.push(`/search/${keywords}`)
        dispatch(searchAction.updateSearch(keywords))
      }
    }
  }

  useEffect(()=>{
    if(params.keywords){
      dispatch(searchAction.updateSearch(params.keywords))
    }else{
      dispatch(searchAction.updateSearch(""))
    }
  setKeywords(reduxKeywords.search)
    
  },[reduxKeywords.search, params.keywords])

  const changeHandle = (e) =>{
    setKeywords(e.target.value)
  }

  return (
    <div>
      <input className="search-input" type="text" ref={searchKey}
        onKeyUp={ keyUpHandle} value={keywords} onChange={changeHandle}
      />
    </div>
  )
}

export default withRouter(SearchInput)
